package vikaa.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import vikaa.adapter.AdapterRecommandWowo;
import vikaa.bean.Space;
import vikaa.bean.SpaceOauth;
import vikaa.timelinepackage.Timeline;
import vikaa.tools.HttpUtil;
import vikaa.wowo.R;
import vikaa.wowo.cache.UserInfoSharePreference;

public class WowoRecommand extends Activity implements OnItemClickListener{
	private ListView wowolistview;
	private AdapterRecommandWowo mAdapter;
	private ArrayList<Space> mList = new ArrayList<Space>();
	private static String uid;
	public static boolean isrefresh = false;
	public static boolean crashflag = false;
	private ImageView lookaroundBtn;
	private LinearLayout backBtn;
	private LinearLayout header;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recommendwowo);
		uid = UserInfoSharePreference.getUid(WowoRecommand.this);
		initview();
		new downMywowoThread().start();
	}
		
	public void initview(){
		header = (LinearLayout)findViewById(R.id.header);
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
		lookaroundBtn = (ImageView)findViewById(R.id.lookaound);
		lookaroundBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				header.setVisibility(View.VISIBLE);
				//DialogService.showProgressDialog(WowoRecommand.this, getString(R.string.get_wowo_list));
				new downMywowoThread().start();
			}
		});
		wowolistview = (ListView) findViewById(R.id.wowolist);
		wowolistview.setOnItemClickListener(this);
		
		mAdapter = new AdapterRecommandWowo(WowoRecommand.this, mList, wowolistview);
        wowolistview.setAdapter(mAdapter);
        
		//DialogService.showProgressDialog(WowoRecommand.this, getString(R.string.get_wowo_list));
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				mList.clear();
				header.setVisibility(View.GONE);
				mAdapter.notifyDataSetChanged();
				break;
			case 2:
				mList.clear();
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					ArrayList<Space> strings = (ArrayList<Space>) msg.obj;
					if(!strings.isEmpty()){
						mList.addAll(strings);
						mAdapter.notifyDataSetChanged();
						wowolistview.setSelection(0);
					}
				}
				break;
			case 3://info = null
				header.setVisibility(View.GONE);
				TextView tv1 = (TextView)findViewById(R.id.emptyTv);
				TextView tv2 = (TextView)findViewById(R.id.emptydivider);
				tv1.setVisibility(View.VISIBLE);
				tv2.setVisibility(View.VISIBLE);
				break;
			case 4://access error
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					Toast.makeText(WowoRecommand.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(WowoRecommand.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5://network error
				header.setVisibility(View.GONE);
				Toast.makeText(WowoRecommand.this, getString(R.string.network_crash), Toast.LENGTH_SHORT).show();
				break;
			case 0://refresh fail
				Toast.makeText(WowoRecommand.this, getString(R.string.info_msg2), Toast.LENGTH_SHORT).show();
				break;
			}
		}
		
	};
	class downMywowoThread extends Thread{
		private boolean isrun = true;
		
		@Override
		public void run() {
			while(isrun){
			isrun =false;
			Map<String, String> map = new HashMap<String, String>();
			map.put("max_count", "10");
			String url = HttpUtil.BASE_URL + "space/popular";
			try {
				ArrayList<Space> List = new ArrayList<Space>();
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				String result = jsonObj.getString("result");
				if(result.equals("1")){
					JSONArray mySpacelist = jsonObj.getJSONArray("info");
					for(int i=0;i<mySpacelist.length();i++){
						Space list = new Space();
						list.setCount(mySpacelist.getJSONObject(i).getString("twitterCount"));
						list.setNumber(mySpacelist.getJSONObject(i).getString("memberCount"));
						list.setManagerCount(mySpacelist.getJSONObject(i).getString("managerCount"));
						list.setTotalMemberCount(String.valueOf(Integer.valueOf(list.getNumber())+Integer.valueOf(list.getManagerCount())));
						list.setSpace_id(mySpacelist.getJSONObject(i).getString("space_id"));
						list.setSpacename(StringEscapeUtils.unescapeHtml4(mySpacelist.getJSONObject(i).getString("spacename")));
						String cover = mySpacelist.getJSONObject(i).getString("cover");
						list.setCover(cover);
						list.setState(mySpacelist.getJSONObject(i).getString("state"));
						ArrayList<SpaceOauth> solist = new ArrayList<SpaceOauth>();
						for(int j =0;j<mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").length();j++){
							SpaceOauth so = new SpaceOauth();
							so.setUid(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("uid"));
							so.setCredits(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("credits"));
							so.setRole(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("role"));
							so.setCallname(mySpacelist.getJSONObject(i).getJSONArray("spaceoauth").getJSONObject(j).getString("callname"));
							solist.add(so);
							}
						list.setSpaceoauth(solist);
						List.add(list);
					}
					Message msg = mhandler.obtainMessage(2);
					msg.obj = List;
					msg.sendToTarget();
				}
				else if(result.equals("0")){
					Message msg = mhandler.obtainMessage(4);
					msg.obj = jsonObj.getString("msg");
					msg.sendToTarget();
				}
				else{
					Message msg = mhandler.obtainMessage(5);
					msg.obj = jsonObj.getJSONObject("info").getString("error");
					msg.sendToTarget();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			}
		}
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		for(Space space : Mywowo.mList){
			if(mList.get(position).getSpace_id() .equals(space.getSpace_id()) ){
				for(SpaceOauth so:space.getSpaceoauth()){
					if(uid.equals(so.getUid())){
						Intent intent = new Intent(WowoRecommand.this,Timeline.class);
				        intent.putExtra("sid", space.getSpace_id());
				        intent.putExtra("uid", uid);
				        intent.putExtra("role", so.getRole());
				        intent.putExtra("spacename", space.getSpacename());
				        intent.putExtra("count", space.getCount());
				        intent.putExtra("cover", mList.get(position).getCover());
				        intent.putExtra("member", mList.get(position).getNumber());
				        intent.putExtra("host", mList.get(position).getManagerCount());
				        intent.putExtra("state", mList.get(position).getState());
				        startActivity(intent);
				        return;
					}
				}
			}
		}
		if(mList.get(position).getState().equals("1")){
			Toast.makeText(WowoRecommand.this, getString(R.string.msg_noaccess_look), Toast.LENGTH_SHORT).show();
		}else{
			Log.i("sdf", mList.get(position).getState());
			String id = mList.get(position).getSpace_id();
	    	String spacename = mList.get(position).getSpacename();
	    	String count = mList.get(position).getCount();
	        Intent intent = new Intent(WowoRecommand.this,Timeline.class);
	        intent.putExtra("sid", id);
	        intent.putExtra("uid", uid);
	        intent.putExtra("role", "0");
	        intent.putExtra("spacename", spacename);
	        intent.putExtra("count", count);
	        intent.putExtra("cover", mList.get(position).getCover());
	        intent.putExtra("member", mList.get(position).getNumber());
	        intent.putExtra("host", mList.get(position).getManagerCount());
	        intent.putExtra("state", mList.get(position).getState());
	        intent.putExtra("accept", 0);
	        startActivity(intent);
		}
	}
}
